﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static MainWindow _instance = new MainWindow();
        private static Dictionary<string, Frame> pageDict;

        /// <summary>
        /// 上一次登录的用户 
        /// </summary>
        static long lastLoginAccount;

        /// <summary>
        /// 主窗口实例。单例模式
        /// </summary>
        /// 创建时间：2022-12-29 11:39:18；
        internal static MainWindow Instance
        {
            get
            {
                return _instance;
            }
        }

       // /// <summary>
       // /// 菜单原始宽度
       // /// </summary>
       //private double leftMenuOriginalWidth = 40;

        public MainWindow()
        {
            InitializeComponent();

            //Task.Run(async () =>
            //{
            //    await Task.Delay(100);
            //    await Dispatcher.BeginInvoke(new Action(() => 
            //    { 
            //        leftMenuOriginalWidth = leftMenu.ActualWidth;
            //    }));
            //});

            lastLoginAccount = GetLoginHelpter.CurrentLoginUser().Id;

            if (pageDict == null)
            {
                pageDict = new Dictionary<string, Frame>();
            }

            //首页
            Frame frame = new Frame();
            frame.Source = new Uri(K1.Tag.ToString(), UriKind.Relative);
            frame.BorderThickness = new Thickness(0);
            frame.Margin = new Thickness(10);
            frame.NavigationUIVisibility = NavigationUIVisibility.Hidden;

            pageDict.TryAdd(K1.Tag.ToString(), frame);
            grid1.Children.Add(frame);
            lastClickLabel = K1;
        }

        /// <summary>
        /// 刷新首页数据
        /// </summary>
        /// 创建时间：2022-12-29 18:13:37。作者：王浩力
        internal static event EventHandler RefreshPageHome;

        private void Window_Closed(object sender, EventArgs e)
        {
            //退出时，备份数据库
            try
            {
                string dbBuckUp = MyConfigReader.GetConfigValue("backUp_db_path");
                if (!System.IO.Directory.Exists(dbBuckUp))
                {
                    System.IO.Directory.CreateDirectory(dbBuckUp);
                }
                string time = DateTime.Now.Ticks.ToString().Substring(12);
                string fileBb = $@"snqk_sys_analysis_{DateTime.Now.ToString("yyyyMMdd")  }_{time}.db";
                string run_db_path = MyConfigReader.GetConfigValue("run_db_path");
                string saveDbPath = System.IO.Path.Combine(dbBuckUp, fileBb);
                File.Copy(run_db_path, saveDbPath,true);
            }
            catch (Exception ex)
            {
                var ex1 = ex.InnerException ?? ex;
                LogHelpter.AddLog("备份数据库出错" + ex1.Message, "db_buckup_error");
            }

            //退出程序           
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 上一次点击的菜单
        /// </summary>
        /// 创建时间：2022-11-28 10:16:20。
        static Label? lastClickLabel = null;

        /// <summary>
        /// 命中模块颜色
        /// </summary>
        /// 创建时间：2023-1-5 20:47:48。作者：王浩力
        readonly static Brush ActiveModelColor = new SolidColorBrush(Color.FromRgb(120, 225, 226));


        /// <summary>
        /// 左侧菜单点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var obj = sender as Label;

            //命中的设置为青色
            obj.Style = (Style)this.FindResource("label_leftMenuActive");

            //obj.Background = ActiveModelColor;
            //obj.Background = new SolidColorBrush(Color.FromRgb(0, 255, 177));
            //obj.Background = Brushes.Aqua;  //new SolidColorBrush(Color.A);//青色

            //上一次的菜单颜色还原
            if (lastClickLabel != null && lastClickLabel != obj)
            {
                // lastClickLabel.Background = Brushes.Azure;//没命中颜色
                lastClickLabel.Style = (Style)this.FindResource("label_leftMenu");

                if (pageDict.ContainsKey(lastClickLabel.Tag.ToString()))
                {
                    pageDict[lastClickLabel.Tag.ToString()].Visibility = Visibility.Collapsed;
                }
            }
            //this.frameMain.Refresh();
            //this.frameMain.ReadLocalValue();
            //this.frameMain.Source = new Uri("PageGasAnalysis.xaml",UriKind.Relative);

            if (!pageDict.ContainsKey(obj.Tag.ToString()))
            {
                Frame frame = new Frame();
                frame.Source = new Uri(obj.Tag.ToString(), UriKind.Relative);
                frame.BorderThickness = new Thickness(0);
                frame.Margin = new Thickness(10);
                frame.NavigationUIVisibility = NavigationUIVisibility.Hidden;

                pageDict.TryAdd(obj.Tag.ToString(), frame);
                grid1.Children.Add(frame);
            }
            pageDict[obj.Tag.ToString()].Visibility = Visibility.Visible;

            //如果是首页，则刷新
            if (obj == K1)
            {
                pageDict[obj.Tag.ToString()].Refresh();
            }

            lastClickLabel = obj;
        }


        //退出登录
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var op = MessageBox.Show("确认退出吗？", "退出提示", MessageBoxButton.OKCancel);
            if (op != MessageBoxResult.OK)
            {
                e.Handled = true;
                return;
            }
            lastLoginAccount = GetLoginHelpter.CurrentLoginUser().Id;

            System.Runtime.Caching.MemoryCache.Default.Remove(CommonConfig.LoginUserCacheKey);
            this.Hide();

            //显示登录窗口 
            Login login = new Login();
            login.Show();
        }

        private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var win = sender as Window;
            if (win.Visibility == Visibility.Visible)
            {
                //当前登录用户姓名
                string user = GetLoginHelpter.CurrentLoginUser().User_real_name;
                if (GetLoginHelpter.CurrentLoginUser() != null && !GetLoginHelpter.CurrentLoginUser().User_account.Equals(CommonConfig.SupperUserAccount))
                {
                    user += "(" + GetLoginHelpter.CurrentLoginUser().Role_id + ")";
                }
                labelUserName.Content = user;
                //lastLoginAccount = GetLoginHelpter.CurrentLoginUser().Id;

                //如果是超级管理员才有模块：账号管理，字典数据
                if (GetLoginHelpter.CurrentLoginUser() == null)
                {
                    K8.Visibility = Visibility.Collapsed;//账号管理
                    K9.Visibility = Visibility.Collapsed;//数据字典
                }
                else if (GetLoginHelpter.CurrentLoginUser().User_account.Equals(CommonConfig.SupperUserAccount))
                {
                    K8.Visibility = Visibility.Visible;//账号管理
                    K9.Visibility = Visibility.Visible;//数据字典
                }
                else
                {
                    K8.Visibility = Visibility.Collapsed;//账号管理
                    K9.Visibility = Visibility.Collapsed;//数据字典
                }

                if (lastClickLabel != null)
                {
                    //lastClickLabel.Background = Brushes.Azure;//未命中
                    lastClickLabel.Style = (Style)this.FindResource("label_leftMenu");
                }

                //K1.Background = ActiveModelColor;//命中颜色 
                //修改时间：2023-1-6 10:25:00。
                K1.Style = (Style)this.FindResource("label_leftMenuActive");

                //刷新首页数据
                //RefreshPageHome?.Invoke(this, new EventArgs());

                //注释时间：2023-1-3 18:52:50
                //this.frameMain.Source = new Uri("PageHome.xaml", UriKind.Relative);
                //if (lastClickLabel == K1)
                //{
                //    this.frameMain.Refresh();
                //}                
                //if (lastClickLabel == K1)
                //{
                //    pageDict[K1.Tag.ToString()].Refresh();
                //    //this.frameMain.Refresh();
                //}

                //展示首页页面
                pageDict[K1.Tag.ToString()].Visibility = Visibility.Visible;
                pageDict[K1.Tag.ToString()].Refresh();

                //其他模块隐藏
                if (lastClickLabel != null && lastClickLabel != K1)
                {
                    pageDict[lastClickLabel.Tag.ToString()].Visibility = Visibility.Collapsed;
                }

                //切换了账号，刷新所有页面。2023-1-4 10:23:02
                if (lastLoginAccount != GetLoginHelpter.CurrentLoginUser().Id)
                {
                    foreach (var item in pageDict)
                    {
                        if (item.Value.Source.ToString() == K1.Tag.ToString()) continue;
                        item.Value.Refresh();
                    }
                }

                lastClickLabel = K1;

                //初始化点击：首页。后台代码触发          
                //// K1.RaiseEvent(new RoutedEventArgs(MouseLeftButtonUpEvent));
                //K1.RaiseEvent(
                //        new System.Windows.Input.MouseButtonEventArgs(
                //        Mouse.PrimaryDevice, 1, MouseButton.Left)
                //        {
                //            RoutedEvent = MouseLeftButtonUpEvent
                //        }
                //    );

            }
        }

        /// <summary>
        /// 折叠左侧菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuFurlButton_Click(object sender, RoutedEventArgs e)
        {
            var button= sender as Button;
            if (leftMenu.Width == 32)
            {
                //展开
                leftMenu.Width = 177; //double.NaN;//double.NaN 自动宽度
                button?.Content = "收起";
            }
            else
            {
                //折叠，收起
                leftMenu.Width = 32;
                button?.Content = "展开";
            }
             

        }
    }
}
